import TWEEN from './tween.js';

var ZW_Ctx;
var angle = 0;
var ZW_PicArray = [];
var goodsArray = [];
var ZW_Offset = 30;
var ZW_PointsArray = [];
var ZW_Info;
var ZW_PixelRatio = 2;
var gIsIphone = false;

var ZW_ClickNodeName = '';
var ZW_HoldNodeName = '';       //长按得珠子名称
var ZW_HoldIndex = 0;   //长按得珠子所在的索引值
var ZW_bHold = false;
var ZW_bLoading = false;  //是否正在加载图片

var Scene_OffsetX = 0;
var Scene_OffsetY = 0;

var Scene_ScaleX = 1.0;
var Scene_ScaleY = 1.0;

var ZW_ClickPos;

var ZW_CurrentPos = 0;

var ZW_Close_Url = '../../../img/close.png';
var ZW_Scale_Url = '../../../img/scale.png';
var ZW_Rot_Url = '../../../img/rotation.png';

var ZW_bTipEdit = true;

var ZW_MoveType = '';

var ZW_tipArray = []; //贴纸名称数组，需要保证不重复
var ZW_tipNumArray = [];  //用于贴纸加载时的计数
var that;

var Load_URL_Num = 0;
var Load_URL_Num0 = 0;

function addBackgroundByData(inData) {
  RemoveImage('back1');

  AddGifImage('back1', app.globalData.baseUrl + inData.scenebackGifImage,
    ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
    ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, true, 0);

  that.setData({
    backGifUrl: app.globalData.baseUrl + inData.scenebackGifUrl,
    backBottomUrl: app.globalData.baseUrl + inData.sceneBackBottomUrl,
  });
}

function RemoveImage(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (tag == ZW_PicArray[i].tag) {
      ZW_PicArray.splice(i, 1);
      i--;
    }
  }
}

function SetImageVisible(tag, visible) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (tag == ZW_PicArray[i].tag) {
      ZW_PicArray[i].visible = visible;
    }
  }
}

function AddGifImage(tag, url, x, y, width, height, rot, scale, visible, order) {
  let contentPicNetPath = url;

  var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale, visible: visible, renderOrder: order };
  ZW_PicArray.unshift(cImage);

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;
      }
  })
}

function AddImage(tag, url, x, y, width, height, rot, scale, visible, order) {
  RemoveImage(tag);
  if (!order) order = 0;
  let contentPicNetPath = url;

  var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale, visible: visible, renderOrder: order };
  ZW_PicArray.push(cImage);

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;

        //ZW_PicArray.push({tag:tag,x:x,y:y,width:width,height:height,url:res.path,rot:rot,scale:scale});
        //console.log(ZW_PicArray);
      }
  })
}

function AddExpression(name) {

  for (var i = 0; i < 5; i++) {
    RemoveImage('expression-' + i);
  }

  //   AddImage('expression1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/expression/ex2/female02-0.png', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.85,
  //   ZW_Info.windowWidth * 0.5 * 1.4, ZW_Info.windowWidth * 1.4, 0, 1.0,true);

  var gifUrlArray = [];
  for (var i = 0; i < 5; i++) {
    gifUrlArray.push(name + '-' + i + '.png');

    if (i == 0) {
      AddGifImage1('expression-' + i, gifUrlArray[i], ZW_Info.windowWidth * 0.526, ZW_Info.windowWidth * 0.462,
        ZW_Info.windowWidth * 0.5333 * 0.55, ZW_Info.windowWidth * 0.42666 * 0.55, 0, 1.0, false, 4);
    } else {
      AddGifImage1('expression-' + i, gifUrlArray[i], ZW_Info.windowWidth * 0.526, ZW_Info.windowWidth * 0.462,
        ZW_Info.windowWidth * 0.5333 * 0.55, ZW_Info.windowWidth * 0.42666 * 0.55, 0, 1.0, false, 4);
    }

  }
}

function AddGifImage1(tag, url, x, y, width, height, rot, scale, visible, order) {
  let contentPicNetPath = url;

  var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale, visible: visible, renderOrder: order };
  ZW_PicArray.push(cImage);

  Load_URL_Num0++;

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;

        Load_URL_Num0--;
        if (Load_URL_Num0 == 0) {

          var coords = { x: 4 };
          new TWEEN.Tween(coords)
            .to({ x: 0 }, 1000 * 5.0 / 15.0)
            .repeat(Infinity).repeatDelay(1200)
            .easing(TWEEN.Easing.Linear.None)
            .onUpdate(function () {
              var num = Math.round(coords.x) % 5;

              for (var i = 4; i > -1; i--) {
                SetImageVisible('expression-' + i, false);
              }

              SetImageVisible('expression-' + num, true);
            })
            .delay(0)
            .start();
        }
      }
  })
}

function ShowProcess() {
  let isImageLoaded = true;
  ZW_PicArray.sort(function (a, b) { return a.renderOrder - b.renderOrder });
  ZW_Ctx.scale(Scene_ScaleX, Scene_ScaleY);
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].url != '' && ZW_PicArray[i].visible) {

      if (ZW_PicArray[i].type == 'tip') {
        let contentPicLocalPath = ZW_PicArray[i].url;

        ZW_Ctx.translate(ZW_PicArray[i].x0 + Scene_OffsetX, ZW_PicArray[i].y0 + Scene_OffsetY);
        ZW_Ctx.rotate(ZW_PicArray[i].rot0 * Math.PI / 180);
        ZW_Ctx.scale(ZW_PicArray[i].scale0, ZW_PicArray[i].scale0);

        ZW_Ctx.translate(ZW_PicArray[i].x, ZW_PicArray[i].y);
        ZW_Ctx.drawImage(contentPicLocalPath, -ZW_PicArray[i].scale * ZW_PicArray[i].width / 2,
          -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2, ZW_PicArray[i].width * ZW_PicArray[i].scale, ZW_PicArray[i].height * ZW_PicArray[i].scale);

        if (ZW_bTipEdit && ZW_PicArray[i].tag.indexOf(Current_Tip_Tag + '-') == 0) {  //只有选中的贴纸才显示边框和按钮
          //贴纸画框
          ZW_Ctx.setStrokeStyle("#ffffff");
          ZW_Ctx.setLineWidth(2.0 / ZW_PicArray[i].scale0);
          ZW_Ctx.rect(-ZW_PicArray[i].scale * ZW_PicArray[i].width / 2,
            -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2, ZW_PicArray[i].width * ZW_PicArray[i].scale, ZW_PicArray[i].height * ZW_PicArray[i].scale);
          ZW_Ctx.stroke();

          //画删除按钮
          ZW_Ctx.drawImage(ZW_Close_Url, -ZW_PicArray[i].scale * ZW_PicArray[i].width / 2 - 12.0 / ZW_PicArray[i].scale0,
            -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2 - 12.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0);

          //画缩放按钮
          ZW_Ctx.drawImage(ZW_Scale_Url, ZW_PicArray[i].width * ZW_PicArray[i].scale - ZW_PicArray[i].scale * ZW_PicArray[i].width / 2 - 12.0 / ZW_PicArray[i].scale0,
            -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2 - 12.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0);

          //画旋转按钮
          ZW_Ctx.drawImage(ZW_Rot_Url, ZW_PicArray[i].width * ZW_PicArray[i].scale - ZW_PicArray[i].scale * ZW_PicArray[i].width / 2 - 12.0 / ZW_PicArray[i].scale0,
            ZW_PicArray[i].height * ZW_PicArray[i].scale - ZW_PicArray[i].scale * ZW_PicArray[i].height / 2 - 12.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0);
        }

        ZW_Ctx.translate(-ZW_PicArray[i].x, -ZW_PicArray[i].y);

        ZW_Ctx.scale(1.0 / ZW_PicArray[i].scale0, 1.0 / ZW_PicArray[i].scale0);
        ZW_Ctx.rotate(-ZW_PicArray[i].rot0 * Math.PI / 180);
        ZW_Ctx.translate(-ZW_PicArray[i].x0 - Scene_OffsetX, -ZW_PicArray[i].y0 - Scene_OffsetY);
      } else {
        let contentPicLocalPath = ZW_PicArray[i].url;

        ZW_Ctx.translate(ZW_PicArray[i].x + Scene_OffsetX, ZW_PicArray[i].y + Scene_OffsetY);
        ZW_Ctx.rotate(ZW_PicArray[i].rot * Math.PI / 180);
        ZW_Ctx.drawImage(contentPicLocalPath, -ZW_PicArray[i].scale * ZW_PicArray[i].width / 2,
          -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2, ZW_PicArray[i].width * ZW_PicArray[i].scale, ZW_PicArray[i].height * ZW_PicArray[i].scale);
        ZW_Ctx.rotate(-ZW_PicArray[i].rot * Math.PI / 180);
        ZW_Ctx.translate(-ZW_PicArray[i].x - Scene_OffsetX, -ZW_PicArray[i].y - Scene_OffsetY);
      }
    } else {
      isImageLoaded = false;
    }
  }
  ZW_Ctx.draw();
  return isImageLoaded;
}

function animation() {
  var times = 0
  var i = setInterval(function () {

    TWEEN.update();

    ShowProcess();
  }, 20)
}



var app = getApp();
// import testData from "../utils/testPersonData.js"
import { bodyLays } from "../../utils/testPersonData"
var mfApi = require('../../../api/api.js');

var lastX = null, lastY = null, lastZ = null;
var sensitive = sensitive || 300;  // 所需力度，xyz偏移值
// var timeGap = timeGap || 200;     // 两次之间时间间隔


Page({
  data: {
    mShouldPlaySound: app.globalData.shouldPlaySound,
    isIndexFrontAniEnd: false,
    isBottomFrontAniEnd: false,
    isRightFrontAniEnd: false,
    showBodyLays: bodyLays,

    baseUrl: app.globalData.baseUrl,
    mShakeImageUrls: [
      "/boxIndex/shake_one.png",
      "/boxIndex/shake_one.png",
      "/boxIndex/shake_two.png",
      "/boxIndex/shake_three.png",
      "/boxIndex/shake_four.png",
      "/boxIndex/shake_five.png",
      "/boxIndex/shake_six.png",
    ],

    // 摇一摇状态  -1初始状态 0摇动结束 1启动摇动
    shakeStatus: -1,
    // 剩余摇一摇次数
    mShakeRemainTimes: app.globalData.gShakeRemaintimes,
    // 摇一摇提示
    mShowShakeTip: false,
    // 上次摇一摇时间戳
    mLastShakeTimeStamp: 0,

    //  截图临时路径
    shotImageUrl: '',

    // 底部商品框 先做动画  动画结束后再iffalse
    isShowBottomGoodsView: false,
    isShowBottomGoodsAni: false
  },
  onLoad: function () {
    console.log('onLoad');

    // 组件实例
    this.indexView = this.selectComponent("#index-ani-lay"); //组件的id
    this.bottomView = this.selectComponent("#index-bottom-lay"); //组件的id
    this.rightView = this.selectComponent("#index-right-lay"); //组件的id
    this.freeDressView = this.selectComponent("#index-person-lay"); //组件的id

    // 右侧菜单弹出动画  
    var tempRightAnimation = jd.createAnimation({
      duration: 200,
      timingFunction: 'cubic-bezier(0,0.14,1,0.18)',
      delay: 100
    });
    tempRightAnimation.opacity(1.0).translate(-50, 0).step()

    let _self = this;
    // 右侧菜单延迟开始
    setTimeout(() => {
      _self.setData({
        rightAnimation: tempRightAnimation.export()
      })
    }, 500);

    this.setData({
      mShouldPlaySound: app.globalData.shouldPlaySound
    })

    ZW_Ctx = jd.createCanvasContext('indexcanvas')

    ZW_Info = jd.getSystemInfoSync();
    console.log(ZW_Info);
    gIsIphone = ZW_Info.platform == "ios";

    ZW_PixelRatio = ZW_Info.pixelRatio;
    that = this;

    this.setData({
      canvasWidth: ZW_Info.windowWidth,
      canvasHeight: ZW_Info.windowHeight * 0.7,
    });

    this.userLogin();
  },

  onShow() {
    this.setData({
      mShouldPlaySound: app.globalData.shouldPlaySound,
      mShakeRemainTimes: app.globalData.gShakeRemaintimes,
    })
    if (this.data.mShakeRemainTimes > 0)
      jd.onAccelerometerChange(this.onAccelerometerChange)
  },

  onHide() {
    jd.stopAccelerometer();
  },

  onSoundClick() {
    app.globalData.shouldPlaySound = !app.globalData.shouldPlaySound;
    this.setData({
      mShouldPlaySound: app.globalData.shouldPlaySound
    })

    if (app.globalData.shouldPlaySound)
      app.startPlaySound();
    else
      app.stopPlaySound();
  },

  onAccelerometerChange(res) {
    // console.log("onAccelerometerChange --- ")
    // 非震动结束 不执行
    if (this.data.shakeStatus != 0) return;
    // 2s内 不执行
    let timestamp = new Date().getTime();//返回数值单位是毫秒；
    if (timestamp - this.data.mLastShakeTimeStamp < 5000) return;
    // 商品弹窗出现时  不执行
    if(this.data.isShowBottomGoodsView) return;

    // res = res.accelerationIncludingGravity;
    var currentTime;
    var timeDifference;
    var deltaX = 0, deltaY = 0, deltaZ = 0;
    if ((lastX === null) && (lastY === null) && (lastZ === null)) {
      lastX = res.x; lastY = res.y; lastZ = res.z; return;
    }
    deltaX = Math.abs(lastX - res.x) * 100;
    deltaY = Math.abs(lastY - res.y) * 100;
    deltaZ = Math.abs(lastZ - res.z) * 100;
    if (((deltaX > sensitive) && (deltaY > sensitive)) ||
      ((deltaX > sensitive) && (deltaZ > sensitive)) ||
      ((deltaY > sensitive) && (deltaZ > sensitive))) {
      // currentTime = new Date();
      // timeDifference = currentTime.getTime() - lastTime.getTime();

      // if (timeDifference > timeGap) {
      //   fn && fn(true);
      //   lastTime = new Date();
      // }
      // else
      //   fn && fn(false)
      if (this.data.mShakeRemainTimes > 0) {
        this.onStartShakeAction();
      } else {
        this.showShakeTip();
      }
      
      this.setData({
        mLastShakeTimeStamp: new Date().getTime()
      })
      lastX = null;
      lastY = null;
      lastZ = null;

    }
    lastX = res.x; lastY = res.y; lastZ = res.z;
  },

  /**
   * 右侧菜单动画结束后 中间主要部分alpha动画显示出来
   */
  // doMainAlphaAni() {
  //   var tempAlphaAnimation = jd.createAnimation({
  //     duration: 500,
  //     timingFunction: 'cubic-bezier(0,0.14,1,0.18)',
  //     delay: 0
  //   });
  //   tempAlphaAnimation.opacity(1.0).step()

  //   this.setData({
  //     mainAnimation: tempAlphaAnimation.export()
  //   })
  // },

  /**
   * 中间上移盒子动画结束
   * 盒子动画结束后隐藏盒子组件
   */
  onIndexAniEnd() {
    console.log("index --- onIndexAniEnd")
    this.setData({
      isIndexFrontAniEnd: true,
    })
  },

  /**
   * 底部选择gender下移动画结束
   * gender下移动画结束后隐藏gender组件
   */
  onBottomAniEnd() {
    console.log("index --- onBottomAniEnd")
    this.setData({
      isBottomFrontAniEnd: true,
    })
  },

  /**
   * 右侧动画结束
   */
  onRightAniEnd() {
    console.log("index --- onRightAniEnd")
    this.setData({
      isRightFrontAniEnd: true,
    })
    // this.doMainAlphaAni();
  },

  /**
   * 底部选中性别
   * @param {*} inData 
   */
  onGenderSelect(inData) {
    if (app.globalData.userInfo == null) {
       jd.showToast({
         title: "checkUser授权失败,请重新进入小程序",
         icon: 'none'
       })
       return
    }

    // mfApi.uploadFile(mfApi.uploadFileUrl(), "")

    app.globalData.selectGender = inData.detail.gender;
    this.indexView.startFrameAni();
    this.bottomView.startFrameAni();
    this.freeDressView.startRandomAni(2000);

    this.setData({
      shakeStatus: -1,
    })
  },

  /**
   * 摇一摇  启动动画
   */
  onStartShakeAction() {
    this.freeDressView.startRandomAni(3000);
    this.setData({
      shakeStatus: 1,
    })
    jd.stopAccelerometer();
    jd.vibrateLong();

    let tempTimes = this.data.mShakeRemainTimes;
    tempTimes--;
    tempTimes = tempTimes >= 0 ? tempTimes : 0;
    this.setData({
      shakeStatus: 1,
      mShakeRemainTimes: tempTimes
    })
    app.globalData.gShakeRemaintimes = tempTimes;
  },

  /**
   * 摇一摇 小人换装动画结束
   */
  onShakeActionEnd(inData) {
    console.log("onShakeActionEnd", inData.detail)

    let tempTimes = this.data.mShakeRemainTimes;
    // tempTimes--;
    // tempTimes = tempTimes >= 0 ? tempTimes : 0;
    this.setData({
      shakeStatus: 0,
      showBodyLays: inData.detail.showBodyLays,
    })
    jd.onAccelerometerChange(this.onAccelerometerChange)

    app.changeSoundSource();
  },

  /**
   * 摇一摇次数用完的提示
   */
  showShakeTip() {
    this.setData({
      mShowShakeTip: true
    })
  },

  hideShakeTip() {
    this.setData({
      mShowShakeTip: false
    })
  },

  onInfoEnterClick() {
    jd.navigateTo({
      url: "/pages/magicBox/gameInfo/gameInfo"
    });
  },

  onToDiyClick() {
    app.globalData.gShowBodyLays = JSON.parse(JSON.stringify(this.data.showBodyLays))

    console.log(app.globalData.gShowBodyLays)
    jd.navigateTo({
      url: "/pages/magicBox/freeWear/freeWear"
    });
  },

  onToShareClick() {
    jd.showLoading();
    this.copyContentToCanvas().then(res => {
      console.log("onToShareClick === copyContentToCanvas === ", res)
      jd.showLoading();
      if (res.code != 0) {
        jd.showToast({
          title: '复制内容出错'
        });
        return;
      }
      this.onGetShot("share");
    });
  },

  onToAddCartClick() {
    let temp = [];
    this.data.showBodyLays.forEach(element => {
      if (element.partDesc)
        temp.push(element)
    });

    if (temp.length == 0) {
      jd.showToast({
        title: "没有可选的商品。"
      })
      return;
    }

    jd.navigateTo({
      url: "../../addCartPage/addCartPage?dataStr=" + JSON.stringify(temp)
    })
  },

  onToAddMyClick() {
    this.shotCanvasImage();
  },

  copyContentToCanvas() {
    // jd.showLoading();
    let _self = this;
    return new Promise(function (resolve, reject) {
      let backData = _self.data.showBodyLays.find(e => {
        return e.partId == "background"
      })

      addBackgroundByData(backData);

      for (let i = 0; i < _self.data.showBodyLays.length; i++) {
        let temp = _self.data.showBodyLays[i];
        if (temp.partId == "background")
          continue;

        if (!temp.partImage || temp.partImage.length == 0)
          continue;

        if (temp.partId != "expression") {
          AddImage(
            temp.partId,
            _self.data.baseUrl + temp.partImage,
            ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.827,
            ZW_Info.windowWidth * 1.3, ZW_Info.windowWidth * 1.3,
            0, 1.0,
            true, i + 1);
        } else {
          // AddExpression(this.data.baseUrl + temp.partSourcePath);
          AddImage(
            temp.partId,
            _self.data.baseUrl + temp.partSourcePath + '-0.png',
            ZW_Info.windowWidth * 0.526, ZW_Info.windowWidth * 0.462,
            ZW_Info.windowWidth * 0.5333 * 0.55, ZW_Info.windowWidth * 0.42666 * 0.55, 0, 1.0, true, i + 1);
        }
      }
      // _self.waitForLoadCanvasImage();
      let tempTimes = 0;
      let waitForLoadCanvasImage = () => {
        tempTimes++;
        let re = ShowProcess();
        console.log("waitForLoadCanvasImage --- re = " + re)
        if (!re && tempTimes < 20) {
          setTimeout(() => {
            waitForLoadCanvasImage();
          }, 500);
        } else if (re) {
          resolve({
            code: 0
          });
        } else {
          resolve({
            code: -1
          });
        }
      }

      waitForLoadCanvasImage();
    })
  },

  onGetShot(inType) {
    let _self = this;
    jd.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: ZW_Info.windowWidth,
      height: ZW_Info.windowWidth * 1.76,
      canvasId: 'indexcanvas',
      success: function (resp) {
        jd.showToast({
          title: '截图成功',
          icon: 'success',
          duration: 1500
        })

        _self.data.shotImageUrl = resp.tempFilePath;
        console.log("onGetShot === " + inType)
        if (inType == "share") {
          console.log("onGetShot === showShare " + inType)
          // jd.showShareMenu({
          //   success: (e) => {
          //     console.log("jd  share  ok", e)
          //   },
          //   fail: (e) => {
          //     console.log("jd  share  fail", e)
          //   }
          // })
          console.log("onGetShot === navigateTo " + '../../sharePage/sharePage?shotImagePath=' + _self.data.shotImageUrl)
          jd.navigateTo({
            url: '../../sharePage/sharePage?shotImagePath=' + _self.data.shotImageUrl
          })
        }
        // jd.saveImageToPhotosAlbum({
        //   filePath: resp.tempFilePath,
        //   success(res) {
        //     jd.showToast({
        //       title: '保存成功'
        //     })
        //   }
        // })
      },
      fail: function (res) {
        jd.showToast({
          title: '截图失败'
        })
      }
    });
    return;
  },

  onShareAppMessage(inData) {
    console.log("onShareAppMessage    =-=-=-=-==");
    console.log(inData);
    return {
      mpId: app.globalData.appId,
      title: '分享的标题',
      type: 1,
      desc: '分享的描述、摘要等',
      imageUrl: app.globalData.baseUrl + "/boxIndex/box-btn-addmy.png",
      path: 'page/index/index',
      mpPath: '分享的微信小程序路径',
      channel: 'Wxfriends,Wxmoments',
    }
  },

  onBottomGoodsCloseClick() {
    this.setData({
      isShowBottomGoodsAni: false
    })
  },

  onBottomGoodsViewAniFinish() {
    if (!this.data.isShowBottomGoodsAni) {
      this.setData({
        isShowBottomGoodsView: false
      })
    }
  },

  onPartTipClick(inPartId) {
    this.setData({
      isShowBottomGoodsView: true,
      isShowBottomGoodsAni: true
    })
  },

  handleLongPress() {
    console.log("handleLongPress")
  },

  /**
   * 授权+登录
   */
  userLogin() {
    var _self = this;
    // return;
    //登录
    jd.login({
      success: function (e) {
        console.log("=============jd.login", e)
        jd.getUserInfo({
          success: function (res) {
            console.log("=============jd.getUserInfo", res);
            if (res.userInfo)
              _self.getUserByJdCodeApi(e.code, res.userInfo.nickname);
            else if (res.user_info)
              _self.getUserByJdCodeApi(e.code, res.user_info.nickname);

          },
          fail: function (res) {
            console.log("=============jd.getUserInfo=====fail");
            jd.showToast({
              title: "jdgetUserInfo授权失败,请重新进入小程序",
              icon: 'none'
            })
          }
        });
      },
      fail: function (res) {
        console.log("=============jd.login=====fail");
        jd.showToast({
          title: "jdlogin授权失败,请重新进入小程序",
          icon: 'none'
        })
      }
    });
  },

  /**
   * 获取用户的openid
   * @param {*} inCode 临时code 
   * @param {*} inNick 昵称
   */
  getUserByJdCodeApi(inCode, inNick) {
    mfApi.http(mfApi.getUserByJdCode(), "GET", {
      "code": inCode,
    }).then(result => {
      console.log("getUserByJdCodeApi  --- ok ")
      console.log(result)

      if (result.errCode == 0) {
        app.globalData.userInfo.openId = result.data.openId;
        app.globalData.userInfo.userNick = inNick;
        app.saveTrack('', true);
      } else {
        console.log("getUserByJdCodeApi  --- fail ")
        jd.showToast({
          title: result.msg,
          icon: 'none'
        })
      }
    });
  },
});